package configure

import (
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"github.com/gin-gonic/gin"
	"github.com/pelletier/go-toml/v2"
	"os"
)

const defaultPort = 8601

// Load 加载配置
func Load() error {
	config, err := os.Open(runtime.MainConfig)
	if nil != err && !os.IsNotExist(err) {
		return err
	}

	if os.IsNotExist(err) {
		Configure.Server.Port = defaultPort
		Configure.Server.GinMode = gin.ReleaseMode

		return nil
	}

	defer func() {
		_ = config.Close()
	}()

	if err := toml.NewDecoder(config).Decode(&Configure); nil != err {
		return err
	}

	return nil
}

// SyncToDisk 同步配置到磁盘
func SyncToDisk() error {
	config, err := os.OpenFile(runtime.MainConfig, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if nil != err {
		return err
	}

	defer func() {
		_ = config.Close()
	}()

	if err := toml.NewEncoder(config).Encode(Configure); nil != err {
		return err
	}

	return nil
}
